package com.hillky.serialize.impl;

import com.hillky.exceptions.SerializeException;
import com.hillky.serialize.Serializer;
import lombok.extern.slf4j.Slf4j;

import java.io.*;

@Slf4j
public class JdkSerializer implements Serializer {
    @Override
    public byte[] serialize(Object object) {
        if (object == null) {
            return null;
        }

        try (
                // 将流的定义写在try里面，会自动关闭IO流，不需要再写final
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                ObjectOutputStream outputStream = new ObjectOutputStream(baos)) {
            outputStream.writeObject(object);
            byte[] result = baos.toByteArray();
            if(log.isDebugEnabled()){
                log.debug("对象【{}】jdk序列化已经完成,长度是【{}】",object,result.length);
            }
            return result;
        } catch (IOException e) {
            log.error("序列化对象时发生异常",object);
            throw new SerializeException();
        }

    }

    @Override
    public <T> T deserialize(byte[] bytes, Class<T> clazz) {
        if (bytes == null||clazz==null) {
            return null;
        }

        try (
                // 将流的定义写在try里面，会自动关闭IO流，不需要再写final
                ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
                ObjectInputStream inputStream = new ObjectInputStream(bais)) {


            T object = (T) inputStream.readObject();
            if(log.isDebugEnabled()){
                log.debug("类【{}】反序列化已经完成",clazz);
            }
            return object;
        } catch (IOException | ClassNotFoundException e) {
            log.error("反序列化对象时发生异常");
            throw new SerializeException();
        }

    }
}
